package wangwenjun.phase2.concurrencypattern.readwritelockseparation.demo01;

import wangwenjun.phase2.concurrencypattern.readwritelockseparation.demo01.framework.ReadWriteLockFactory;
import wangwenjun.phase2.concurrencypattern.readwritelockseparation.demo01.framework.Lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ChangLiang
 * @date 2020/6/12
 */
public class ShareData {

    /**
     * 定义共享数据（资源）
     */
    private final List<Character> container = new ArrayList<>();

    /**
     * 创建工厂
     */
    private final ReadWriteLockFactory readWriteLockFactory = ReadWriteLockFactory.createReadWriteLock();

    /**
     * 从工厂获取ReadLock
     */
    private final Lock readLock = readWriteLockFactory.getReadLock();

    /**
     * 从工厂获取WriteLock
     */
    private final Lock writeLock = readWriteLockFactory.getWriteLock();

    private final int length;

    public ShareData(int length) {
        this.length = length;
        for (int i = 0; i < length; i++) {
            container.add(i, 'c');
        }
    }

    public char[] read() throws InterruptedException {
        try {
            readLock.lock();
            char[] buffer = new char[length];
            for (int i = 0; i < length; i++) {
                buffer[i] = container.get(i);
            }
            // mock read time consumption
            TimeUnit.SECONDS.sleep(1);
            return buffer;
        } finally {
            readLock.unlock();
        }
    }

    public void write(char c) throws InterruptedException {
        try {
            writeLock.lock();
            for (int i = 0; i < length; i++) {
                container.add(i, c);
            }
            // mock write time consumption
            TimeUnit.MILLISECONDS.sleep(200);
        } finally {
            writeLock.unlock();
        }
    }


}
